package com.whli.autumn.mall.metadata.service.impl;

import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.whli.autumn.core.app.constant.AppConstants;
import com.whli.autumn.core.exception.BusinessException;
import com.whli.autumn.core.extend.service.impl.BaseServiceImpl;
import com.whli.autumn.mall.metadata.domain.entity.ProductInfo;
import com.whli.autumn.mall.metadata.mapper.ProductInfoMapper;
import com.whli.autumn.mall.metadata.service.IProductInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * <p>商品信息业务实现</p>
 *
 * @author whli
 * @version 1.0.0
 * @since 2023-04-09 09:32
 */
@Service("productInfoService")
public class ProductInfoServiceImpl extends BaseServiceImpl<ProductInfo, ProductInfoMapper> implements IProductInfoService {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean enable(String id) {
        if (StringUtils.isEmpty(id)) {
            return false;
        }
        int rows = mapper.updateStatus(id, AppConstants.YES);
        return SqlHelper.retBool(rows);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean disable(String id) {
        if (StringUtils.isEmpty(id)) {
            return false;
        }
        int rows = mapper.updateStatus(id, AppConstants.NO);
        return SqlHelper.retBool(rows);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String save(ProductInfo productInfo) {
        this.validOneByCode(productInfo.getCode());
        return super.save(productInfo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String update(ProductInfo productInfo) {
        ProductInfo temp = this.getByPK(productInfo.getId());
        if (temp == null) {
            throw new BusinessException("该条数据已删除，请刷新后重新操作");
        }
        if (!temp.getCode().equals(productInfo.getCode())) {
            this.validOneByCode(productInfo.getCode());
        }
        return super.update(productInfo);
    }

    /**
     * <p>验证编码是否存在</p>
     *
     * @author whli
     * @since 2023/4/29 14:32
     * @param code
     * @return
     */
    private void validOneByCode(String code) {
        ProductInfo one = new ProductInfo();
        one.setCode(code);
        one = super.getOne(one);
        if (one != null) {
            throw new BusinessException("商品编码【" + code + "】已存在，请重新输入");
        }
    }

}
